Page({
  data: {
    tempAvatarUrl: '',
    tempNickname: '',
    userIds: {},
    canComplete: false,
    isLoading: false,
    loadingText: '正在处理...',
    returnUrl: ''
  },

  onLoad(options) {
    console.log('首次登录页面加载，参数:', options)
    
    // 获取返回URL
    if (options.returnUrl) {
      this.setData({
        returnUrl: decodeURIComponent(options.returnUrl)
      })
    }
    
    // 生成用户ID
    this.generateUserIds()
  },

  // 生成用户ID
  async generateUserIds() {
    this.setData({
      isLoading: true,
      loadingText: '正在分配用户ID...'
    })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'userManager',
        data: {
          action: 'generateUserId'
        }
      })
      
      if (result.result.success) {
        this.setData({
          userIds: {
            userId: result.result.userId,
            numericId: result.result.numericId,
            userNumber: result.result.userNumber,
            displayId: result.result.displayId
          }
        })
        console.log('用户ID生成成功:', this.data.userIds)
      } else {
        throw new Error(result.result.error || 'ID生成失败')
      }
    } catch (error) {
      console.error('生成用户ID失败:', error)
      wx.showToast({
        title: 'ID生成失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({
        isLoading: false
      })
    }
  },

  // 选择头像
  onChooseAvatar(e) {
    console.log('选择头像:', e.detail.avatarUrl)

    // 设置头像URL
    this.setData({
      tempAvatarUrl: e.detail.avatarUrl
    })

    // 显示成功提示
    wx.showToast({
      title: '头像设置成功！',
      icon: 'success',
      duration: 1500
    })

    // 检查是否可以完成注册
    this.checkCanComplete()

    console.log('✅ 头像设置完成')
  },

  // 输入昵称
  onNicknameInput(e) {
    const nickname = e.detail.value.trim()
    this.setData({
      tempNickname: nickname
    })
    this.checkCanComplete()
  },

  // 检查是否可以完成注册
  checkCanComplete() {
    const { tempNickname, userIds } = this.data
    const canComplete = tempNickname.length >= 2 && userIds.userId
    
    this.setData({
      canComplete: canComplete
    })
  },

  // 完成注册
  async completeRegistration() {
    if (!this.data.canComplete) {
      return
    }
    
    const { tempAvatarUrl, tempNickname, userIds } = this.data
    
    this.setData({
      isLoading: true,
      loadingText: '正在创建账户...'
    })
    
    try {
      // 获取微信登录凭证
      const loginResult = await new Promise((resolve, reject) => {
        wx.login({
          success: resolve,
          fail: reject
        })
      })
      
      console.log('获取登录凭证成功:', loginResult.code)
      
      // 调用云函数创建用户
      const result = await wx.cloud.callFunction({
        name: 'userManager',
        data: {
          action: 'login',
          userInfo: {
            nickName: tempNickname,
            avatarUrl: tempAvatarUrl,
            code: loginResult.code,
            // 预设用户ID信息
            userId: userIds.userId,
            numericId: userIds.numericId,
            userNumber: userIds.userNumber,
            displayId: userIds.displayId,
            // 标记为首次注册
            isFirstRegistration: true
          }
        }
      })
      
      if (result.result.success) {
        // 保存用户信息
        const userInfo = result.result.userInfo
        wx.setStorageSync('userInfo', userInfo)
        wx.setStorageSync('isLoggedIn', true)
        
        console.log('用户注册成功:', userInfo)
        
        wx.showToast({
          title: `欢迎加入，${userInfo.nickName}！`,
          icon: 'success',
          duration: 2000
        })
        
        // 延迟跳转
        setTimeout(() => {
          this.navigateAfterRegistration()
        }, 2000)
        
      } else {
        throw new Error(result.result.error || '注册失败')
      }
      
    } catch (error) {
      console.error('注册失败:', error)
      wx.showToast({
        title: error.message || '注册失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({
        isLoading: false
      })
    }
  },

  // 跳过注册
  async skipRegistration() {
    wx.showModal({
      title: '跳过注册',
      content: '跳过注册将使用默认信息，您可以稍后在个人中心完善信息。确定要跳过吗？',
      success: async (res) => {
        if (res.confirm) {
          await this.createDefaultUser()
        }
      }
    })
  },

  // 创建默认用户
  async createDefaultUser() {
    const { userIds } = this.data
    
    this.setData({
      isLoading: true,
      loadingText: '正在创建默认账户...'
    })
    
    try {
      // 获取微信登录凭证
      const loginResult = await new Promise((resolve, reject) => {
        wx.login({
          success: resolve,
          fail: reject
        })
      })
      
      // 使用默认信息创建用户
      const result = await wx.cloud.callFunction({
        name: 'userManager',
        data: {
          action: 'login',
          userInfo: {
            nickName: '微信用户',
            avatarUrl: '',
            code: loginResult.code,
            userId: userIds.userId,
            numericId: userIds.numericId,
            userNumber: userIds.userNumber,
            displayId: userIds.displayId
          }
        }
      })
      
      if (result.result.success) {
        const userInfo = result.result.userInfo
        wx.setStorageSync('userInfo', userInfo)
        wx.setStorageSync('isLoggedIn', true)
        
        wx.showToast({
          title: '账户创建成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          this.navigateAfterRegistration()
        }, 1500)
        
      } else {
        throw new Error(result.result.error || '创建账户失败')
      }
      
    } catch (error) {
      console.error('创建默认用户失败:', error)
      wx.showToast({
        title: '创建失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({
        isLoading: false
      })
    }
  },

  // 注册后导航
  navigateAfterRegistration() {
    const { returnUrl } = this.data
    
    if (returnUrl) {
      // 有返回URL，跳转到指定页面
      console.log('跳转到返回URL:', returnUrl)
      wx.redirectTo({
        url: returnUrl,
        fail: () => {
          // 如果跳转失败，回到首页
          wx.switchTab({
            url: '/pages/index/index'
          })
        }
      })
    } else {
      // 没有返回URL，跳转到首页
      wx.switchTab({
        url: '/pages/index/index'
      })
    }
  }
})
